﻿using System.Configuration;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Xml;

namespace Logistics.Utility
{
    public static class DBConfig
    {
        /// <summary>
        /// 数据库连接
        /// </summary>
        public static string Connection()
        {
            return ConfigurationManager.ConnectionStrings["context"].ConnectionString;
        }

        /// <summary>
        /// 是否为可信请求
        /// </summary>
        public static bool RquestAccess(HttpRequestMessage request)
        {
            var debug = ConfigurationManager.AppSettings["Debug"] == "true";
            if (debug) return true;
            var hosts = ConfigurationManager.AppSettings["TrustedHosts"].Split(',');
            var clientIP = Generator.GetClientIP(request);
            return !string.IsNullOrWhiteSpace(clientIP) && hosts.Contains(clientIP);
        }

        /// <summary>
        /// 获取服务api的host
        /// </summary>
        public static string GetServiceHost(ApiService service)
        {
            var xml = new XmlDocument();
            xml.Load(HttpContext.Current.Server.MapPath("/App_Setting/ServiceApiHosts.xml"));
            var root = xml.DocumentElement;
            if (root == null) return null;
            var api = root.SelectSingleNode(string.Format("//api[@name='{0}']", service));
            if (api == null) return null;
            var host = api.SelectSingleNode("host");
            return host == null ? null : host.InnerText;
        }
    }
}
